<template>
    <div class="p-2 page-flex">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                        <el-form-item label="合同名称" prop="contractName">
                            <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="业主单位" prop="ownerUnit">
                            <el-input v-model="queryParams.ownerUnit" placeholder="请输入业主单位" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="项目区域" prop="projectRegion">
                            <el-cascader v-model="queryParams.projectRegion" :options="searchRegionOptions"
                                :props="{ lazy: true, lazyLoad: loadSearchRegion, value: 'value', label: 'label', checkStrictly: true }"
                                placeholder="请选择项目区域" style="width: 240px" clearable />
                        </el-form-item>
                        <el-form-item label="合同状态" prop="contractStatus">
                            <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable
                                style="width: 240px">
                                <el-option v-for="dict in contract_status" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="回款状态" prop="receiveIsArrive">
                            <el-select v-model="queryParams.receiveIsArrive" placeholder="请选择回款节点状态" clearable
                                style="width: 240px">
                                <el-option v-for="dict in pro_receive_is_arrive" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="执行总裁" prop="presidentsId">
                            <el-select
                                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                                placeholder="请选择执行总裁" style="width: 240px" clearable
                                @click="showSearchPresidentSelector = true" @clear="clearSearchPresident">
                                <template #empty>
                                    <div style="text-align: center; padding: 10px">
                                        <el-button type="primary" plain @click="showSearchPresidentSelector = true">
                                            选择执行总裁 </el-button>
                                    </div>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="项目负责人" prop="leadersId" label-width="82px">
                            <el-select
                                :model-value="selectedSearchLeader ? selectedSearchLeader.userName || selectedSearchLeader.nickName : ''"
                                placeholder="请选择项目负责人" style="width: 226px" clearable
                                @click="showSearchLeaderSelector = true" @clear="clearSearchLeader">
                                <template #empty>
                                    <div style="text-align: center; padding: 10px">
                                        <el-button type="primary" plain @click="showSearchLeaderSelector = true">
                                            选择项目负责人 </el-button>
                                    </div>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="签订时间" prop="conSignTime" style="width: 308px">
                            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                                style="width: 100%"></el-date-picker>
                        </el-form-item>
                        <el-form-item style="margin-left: auto">
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="never" class="table-card">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport"
                            v-hasPermi="['project:receive:conStatistic']">导出统计</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Download" @click="handleExportDetail"
                            v-hasPermi="['project:receive:export']">导出明细</el-button>
                    </el-col>
                    <!-- 排序控件 -->
                    <el-col :span="12" style="display: flex; align-items: center; gap: 8px">
                        <el-select v-model="sortField" placeholder="选择排序字段" clearable style="width: 170px"
                            @change="handleSortChange">

                            <el-option label="合同名称" value="contractName" />
                            <el-option label="业主单位" value="ownerUnit" />
                            <el-option label="合同签订时间" value="conSignTime" />
                            <el-option label="合同总金额" value="conAmount" />
                            <el-option label="项目负责人" value="proLeadersName" />
                            <el-option label="项目执行总裁" value="proPresidentsName" />
                            <el-option label="收款负责人" value="receiveLeadersName" />
                            <el-option label="合同状态" value="contractStatus" />
                            <el-option label="已达节点总金额" value="arrivedNodeAmount" />
                            <el-option label="已回款金额" value="receivedAmount" />
                            <el-option label="已开票未回款金额" value="noReceiveAmount" />
                        </el-select>
                        <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'"
                            @click="toggleSortOrder" type="info" plain size="small"
                            :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'">
                            {{ sortOrder === 'asc' ? '正序' : '逆序' }}
                        </el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table ref="tableRef" v-loading="loading" :data="conReceiveStatisticList" border height="100%"
                class="flex-table" :header-cell-style="{ 'text-align': 'center' }">
                <el-table-column label="序号" align="center" width="60" fixed="left">
                    <template #default="scope">
                        <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <!-- 1. 合同名称 -->
                <el-table-column label="合同名称" align="left" prop="contractName" width="300" fixed="left">
                    <template #default="scope">
                        <span class="contract-name-text two-line-clamp">{{ scope.row.contractName || '-' }}</span>
                    </template>
                </el-table-column>
                <!-- 2. 业主单位 -->
                <el-table-column label="业主单位" align="center" prop="ownerUnit" width="100" show-overflow-tooltip />
                <!-- 3. 合同签订时间 -->
                <el-table-column label="合同签订时间" align="center" prop="conSignTime" width="110">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.conSignTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>

                <!-- 5. 服务费用及付款方式 -->
                <el-table-column label="服务费用及付款方式" align="left" prop="conAmountRemark" width="200"
                    show-overflow-tooltip />
                <!-- 7. 项目负责人 -->
                <el-table-column label="项目负责人" align="center" prop="proLeadersName" width="120" show-overflow-tooltip />
                <!-- 6. 项目执行总裁 -->
                <el-table-column label="项目执行总裁" align="center" prop="proPresidentsName" width="120"
                    show-overflow-tooltip />
                <!-- 8. 收款负责人 -->
                <el-table-column label="收款负责人" align="center" prop="receiveLeadersName" width="120"
                    show-overflow-tooltip />
                <!-- 9. 合同状态 -->
                <el-table-column label="合同状态" align="center" prop="contractStatus" width="100">
                    <template #default="scope">
                        <dict-tag :options="contract_status" :value="scope.row.contractStatus || ''" />
                    </template>
                </el-table-column>
                <!-- 10. 回款节点状态 -->
                <el-table-column label="回款节点状态" align="center" prop="isArrive" width="100">
                    <template #default="scope">
                        <dict-tag :options="pro_receive_is_arrive" :value="scope.row.isArrive || ''" />
                    </template>
                </el-table-column>
                <!-- 4. 合同总金额 -->
                <el-table-column label="合同总金额" align="center" prop="conAmount" width="180">
                    <template #default="scope">
                        <span class="amount-text contract-amount">{{ formatAmount(scope.row.conAmount) }}元</span>
                    </template>
                </el-table-column>

                <!-- 11. 已达节点总金额（元） -->
                <el-table-column label="已达节点总金额" align="center" prop="arrivedNodeAmount" width="180">
                    <template #default="scope">
                        <span class="amount-text arrived-amount">{{ formatAmount(scope.row.arrivedNodeAmount || 0)
                        }}元</span>
                    </template>
                </el-table-column>
                <!-- 12. 已回款金额（元） -->
                <el-table-column label="已回款金额" align="center" prop="receivedAmount" width="180">
                    <template #default="scope">
                        <span class="amount-text received-amount">{{ formatAmount(scope.row.receivedAmount || 0)
                        }}元</span>
                    </template>
                </el-table-column>
                <!-- 12.1 已开票未回款金额（元） -->
                <el-table-column label="已开票未回款金额" align="center" prop="noReceiveAmount" width="180">
                    <template #default="scope">
                        <span class="amount-text">{{ formatAmount(scope.row.noReceiveAmount || 0) }}元</span>
                    </template>
                </el-table-column>
                <!-- 13. 剩余已达节点应收款金额（元） = 已达节点总金额-已回款金额 -->
                <el-table-column label="剩余已达节点应收款金额" align="center" prop="surplusNodeReceiveAmount" width="180">
                    <template #default="scope">
                        <span class="amount-text remaining-amount">{{ formatAmount(scope.row.surplusNodeReceiveAmount ||
                            0) }}元</span>
                    </template>
                </el-table-column>
                <!-- 14. 剩余合同金额（元） = 合同总金额-已回款金额 -->
                <el-table-column label="剩余合同金额" align="center" prop="surplusConAmount" width="180">
                    <template #default="scope">
                        <span class="amount-text surplus-con-amount">{{ formatAmount(scope.row.surplusConAmount || 0)
                        }}元</span>
                    </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" align="center" width="120" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" text @click="handleEditContractReceive(scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            回款详情
                        </el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无合同回款统计数据" />
                </template>
            </el-table>

            <pagination class="pagination-fixed" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 搜索条件用的总裁选择器 -->
        <UserSelector v-model:visible="showSearchPresidentSelector" title="选择执行总裁"
            :selected-user-ids="queryParams?.presidentsId" :selected-user-names="selectedSearchPresidentName"
            :multiple="false" @confirmWithIds="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />

        <!-- 搜索条件用的项目负责人选择器 -->
        <UserSelector v-model:visible="showSearchLeaderSelector" title="选择项目负责人"
            :selected-user-ids="queryParams?.leadersId" :selected-user-names="selectedSearchLeaderName"
            :multiple="false" @confirmWithIds="handleSearchLeaderConfirm" @cancel="handleSearchLeaderCancel" />

        <!-- 表格滚动控制组件 -->
        <TableScrollControl :table-ref="tableRef" :visible="true" ref="scrollControlRef" />

    </div>
</template>

<script setup name="ConReceiveStatistic" lang="ts">
import { listConReceiveStatistic } from '@/api/project/init/contract';
import { ConReceiveStatisticVO, ProContractQuery } from '@/api/project/init/contract/types';
import { listAddressByParent } from '@/api/project/init/address';
import { parseTime } from '@/utils/ruoyi';
import UserSelector from '@/components/UserSelector/index.vue';
import TableScrollControl from '@/components/TableScrollControl/index.vue';
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const router = useRouter();

// 字典数据
const { contract_status, pro_receive_is_arrive } = toRefs<any>(proxy?.useDict('contract_status', 'pro_receive_is_arrive'));

// 列表数据
const conReceiveStatisticList = ref<ConReceiveStatisticVO[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const searchRegionOptions = ref([]);
const showSearchPresidentSelector = ref(false);
const selectedSearchPresident = ref(null);
const selectedSearchPresidentName = ref('');
const showSearchLeaderSelector = ref(false);
const selectedSearchLeader = ref(null);
const selectedSearchLeaderName = ref('');

// 表格引用和滚动控制组件引用
const tableRef = ref<any>(null);
const scrollControlRef = ref<any>(null);




const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    contractName: undefined,
    ownerUnit: undefined,
    contractStatus: undefined,
    receiveIsArrive: undefined,
    presidentsId: '',
    leadersId: '',
    projectRegion: '',
    proStatus: '3',
    orderByColumn: undefined,
    isAsc: undefined,
    params: {}
});

// 排序相关的状态变量
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('asc'); // 设置默认为正序

// 搜索条件区域数据加载
const loadSearchRegion = async (node, resolve) => {
    try {
        let parentId = 0;
        if (node && typeof node.value === 'number') {
            parentId = node.value;
        } else if (node && node.value !== undefined && node.value !== null) {
            const parsed = parseInt(String(node.value), 10);
            if (!isNaN(parsed)) {
                parentId = parsed;
            }
        }
        const res = await listAddressByParent(parentId);
        const data = res.data || [];
        resolve(
            data.map((item) => ({
                value: item.id,
                label: item.name,
                leaf: false
            }))
        );
    } catch (error) {
        console.error('加载搜索区域数据失败:', error);
        resolve([]);
    }
};

// 搜索条件总裁选择相关
const handleSearchPresidentConfirm = (data) => {
    if (data.users && data.users.length > 0) {
        selectedSearchPresident.value = data.users[0];
        selectedSearchPresidentName.value = data.userNames || '';
        if (queryParams.value) {
            queryParams.value.presidentsId = data.userIds || '';
        }
    } else {
        selectedSearchPresident.value = null;
        selectedSearchPresidentName.value = '';
        if (queryParams.value) {
            queryParams.value.presidentsId = '';
        }
    }
    showSearchPresidentSelector.value = false;
};

const handleSearchPresidentCancel = () => {
    showSearchPresidentSelector.value = false;
};

const clearSearchPresident = () => {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    if (queryParams.value) {
        queryParams.value.presidentsId = '';
    }
};

// 搜索条件项目负责人选择相关
const handleSearchLeaderConfirm = (data) => {
    if (data.users && data.users.length > 0) {
        selectedSearchLeader.value = data.users[0];
        selectedSearchLeaderName.value = data.userNames || '';
        if (queryParams.value) {
            queryParams.value.leadersId = data.userIds || '';
        }
    } else {
        selectedSearchLeader.value = null;
        selectedSearchLeaderName.value = '';
        if (queryParams.value) {
            queryParams.value.leadersId = '';
        }
    }
    showSearchLeaderSelector.value = false;
};

const handleSearchLeaderCancel = () => {
    showSearchLeaderSelector.value = false;
};

const clearSearchLeader = () => {
    selectedSearchLeader.value = null;
    selectedSearchLeaderName.value = '';
    if (queryParams.value) {
        queryParams.value.leadersId = '';
    }
};

/**
 * 格式化金额
 */
const formatAmount = (amount: number | string) => {
    if (amount === null || amount === undefined) return '0.00';
    return Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
};



/** 查询合同回款统计列表 */
const getList = async () => {
    loading.value = true;
    try {
        const params = { ...queryParams.value };
        if (dateRange.value?.length === 2) {
            params.params = {
                ...params.params,
                bSignTime: dateRange.value[0]?.toString(),
                eSignTime: dateRange.value[1]?.toString()
            };
        }
        // 处理项目区域参数
        if (params.projectRegion && Array.isArray(params.projectRegion)) {
            params.projectRegion = params.projectRegion.join(',');
        }
        // 添加排序参数
        if (sortField.value && sortOrder.value) {
            params.orderByColumn = sortField.value;
            params.isAsc = sortOrder.value;
        }

        // 调用真实的API接口
        const res = await listConReceiveStatistic(params);
        conReceiveStatisticList.value = res.rows || [];
        total.value = res.total || 0;

        console.log('获取到的统计数据:', conReceiveStatisticList.value);
        console.log('总数:', total.value);
    } catch (error) {
        console.error('获取合同回款统计列表失败:', error);
        ElMessage.error('获取合同回款统计列表失败');
    } finally {
        loading.value = false;
    }
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
    dateRange.value = ['', ''];
    // 重置搜索条件总裁选择
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    // 重置搜索条件项目负责人选择
    selectedSearchLeader.value = null;
    selectedSearchLeaderName.value = '';
    queryFormRef.value?.resetFields();
    queryParams.value.params = {
        bSignTime: undefined,
        eSignTime: undefined
    };
    // 重置查询参数中的新字段
    queryParams.value.presidentsId = undefined;
    queryParams.value.leadersId = undefined;
    queryParams.value.projectRegion = undefined;
    queryParams.value.contractStatus = undefined;
    queryParams.value.receiveIsArrive = undefined;
    // 重置排序状态
    sortField.value = undefined;
    sortOrder.value = 'asc';
    queryParams.value.orderByColumn = undefined;
    queryParams.value.isAsc = undefined;
    // 保持项目状态参数
    queryParams.value.proStatus = '3';
    handleQuery();
};

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download(
        'pro/contract/receive/statistic/export',
        {
            ...queryParams.value
        },
        `contract_receive_statistic_${new Date().getTime()}.xlsx`
    );
};

/** 导出明细按钮操作 */
const handleExportDetail = () => {
    proxy?.download(
        'pro/contract/receive/detail/export',
        {
            ...queryParams.value
        },
        `contract_receive_detail_${new Date().getTime()}.xlsx`
    );
};



/** 处理编辑合同回款信息 */
const handleEditContractReceive = (row: ConReceiveStatisticVO) => {
    // 跳转到编辑页面，将完整的合同对象通过路由状态传递
    router.push({
        name: 'ReceiveEdit',
        params: {
            conId: row.id.toString()
        },
        state: {
            contractData: JSON.parse(JSON.stringify(row))
        }
    });
};






// 排序相关方法
const handleSortChange = (value: string) => {
    sortField.value = value;
    if (sortOrder.value !== 'asc' && sortOrder.value !== 'desc') {
        sortOrder.value = 'asc';
    }
    handleQuery();
};

const toggleSortOrder = () => {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
    handleQuery();
};

onMounted(() => {
    getList();
});

// 监听数据变化，重新初始化滚动控制
watch(conReceiveStatisticList, () => {
    nextTick(() => {
        setTimeout(() => {
            scrollControlRef.value?.initScrollControl();
        }, 500);
    });
}, { deep: true });
</script>

<style lang="scss" scoped>
.page-flex {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 16px);
}

.table-card {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-height: 0;
}

.table-card :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-height: 0;
}

.flex-table {
    flex: 1;
}

.pagination-fixed {
    margin-top: 8px;
}

.amount-text {
    font-weight: bold;
    font-size: 14px;
}

.contract-amount {
    color: #1f2937;
}

.received-amount {
    color: #059669;
}

/* 已达节点总金额（信息/蓝色） */
.arrived-amount {
    color: #2563eb;
}

.remaining-amount {
    color: #f59e0b;
}

/* 剩余合同金额（风险/红色） */
.surplus-con-amount {
    color: #dc2626;
}

:deep(.el-progress) {
    .el-progress__text {
        font-size: 12px;
        font-weight: bold;
    }
}

/* 基础样式 */
:deep(.el-table) {
    .el-table__cell {
        vertical-align: middle;
    }
}

/* 合同信息单元格样式 */
.contract-info-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px 0;
}

.contract-name {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 8px;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 1px solid #bae6fd;
    transition: all 0.3s ease;
    max-width: 100%;
    overflow: hidden;
}

.contract-name:hover {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    border-color: #409eff;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.contract-icon {
    font-size: 16px;
    color: #0ea5e9;
    flex-shrink: 0;
}

.contract-text {
    font-size: 13px;
    font-weight: 500;
    color: #0c4a6e;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 120px;
}

/* 普通文本显示：支持自动换行，超过两行省略 */
.contract-name-text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-word;
}

.two-line-clamp {
    -webkit-line-clamp: 2;
    line-clamp: 2;
}
</style>